package com.example.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.entity.Collections;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.CollectionsMapper;
import com.example.springboot.service.ICollectionsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class CollectionsService implements ICollectionsService {

    @Autowired //通过autowired导入collectionsMapper
    CollectionsMapper collectionsMapper;

    public List<Collections> list(){
        return collectionsMapper.list();
    }

    @Override
    public PageInfo<Collections> page(BaseRequest baseRequest){
//        dependency引入pagehelper
//        PageHelper传入页面和每页信息条数
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<Collections> collectionss=collectionsMapper.listByCondition(baseRequest);
        return new PageInfo<>(collectionss);
    }

    @Override
    public void save(Collections collections){//        当做卡号来处理
        Date date= new Date();
        try{
            collections.setCategory(category(collections.getCategories()));
            collectionsMapper.save(collections);
        }catch(DuplicateKeyException e){
            log.error("数据插入失败,name:{}",collections.getName());
            throw new ServiceException("用户插入失败");
        }
    }

    private String category(List<String> categories){
        StringBuilder sb = new StringBuilder();
        if(CollUtil.isNotEmpty(categories)){
            categories.forEach(v -> sb.append(v).append(" > "));
            return sb.substring(0,sb.lastIndexOf(" > "));
        }
        return sb.toString();
    }


    @Override
    public Collections getById(Integer id) {
        return collectionsMapper.getById(id);
    }

    @Override
    public void update(Collections collections) {
        collections.setCategory(category(collections.getCategories()));
        collections.setUpdateTime(new Date());
        collectionsMapper.updateById(collections);

    }

    @Override
    public void deleteById(Integer id) {
        collectionsMapper.deleteById(id);
    }
    
}
